package com.atguigu.tingshu.order.api;

import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Tag(name = "订单管理")
@RestController
@RequestMapping("api/order/orderInfo")
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoApiController {

	@Autowired
	private OrderInfoService orderInfoService;



	/**
	 * 确认订单-订单结算页
	 * @param tradeVo
	 * @return
	 */
	@GuiGuLogin
	@Operation(summary = "确认订单")
	@PostMapping("trade")
	public Result trade(@RequestBody TradeVo tradeVo){
		//	谁的订单
		Long userId = AuthContextHolder.getUserId();
		//	调用服务层方法.
		OrderInfoVo orderInfoVo = this.orderInfoService.trade(tradeVo,userId);
		//	返回数据
		return Result.ok(orderInfoVo);
	}

	/**
	 * 立即结算
	 * @param orderInfoVo
	 * @return
	 */
	@GuiGuLogin
	@Operation(summary = "立即结算")
	@PostMapping("submitOrder")
	public Result submitOrder(@RequestBody @Validated OrderInfoVo orderInfoVo){
		//	获取用户Id
		Long userId = AuthContextHolder.getUserId();
		//	调用服务层方法
		String orderNo = this.orderInfoService.submitOrder(orderInfoVo,userId);
		//	前端与后台传递数据通常都是 key-value json 格式！ class Param{ private String orderNo;}
		HashMap<String, Object> map = new HashMap<>();
		map.put("orderNo",orderNo);
		//	返回数据
		return Result.ok(map);
	}

	/**
	 * 查看我的订单
	 * @param orderNo
	 * @return
	 */
	@GuiGuLogin
	@Operation(summary = "根据订单号获取订单信息")
	@GetMapping("getOrderInfo/{orderNo}")
	public Result getOrderInfo(@PathVariable String orderNo){
		//	调用服务层方法.
		OrderInfo orderInfo = this.orderInfoService.getOrderInfoByOrderNo(orderNo);
		return Result.ok(orderInfo);
	}

	/**
	 * 查看我的订单
	 * @param page
	 * @param limit
	 * @return
	 */
	@GuiGuLogin
	@Operation(summary = "获取用户订单")
	@GetMapping("findUserPage/{page}/{limit}") // ?orderStatus=UNPAID PAID
	public Result findUserPage(@PathVariable Long page,
							   @PathVariable Long limit,
							   HttpServletRequest request){
		//	获取到订单状态.
		String orderStatus = request.getParameter("orderStatus");
		//	获取到用户Id
		Long userId = AuthContextHolder.getUserId();
		//	封装Page对象
		Page<OrderInfo> orderInfoPage = new Page<>(page,limit);
		//	调用服务层方法
		IPage<OrderInfo> infoIPage = this.orderInfoService.findUserPage(orderInfoPage,userId,orderStatus);
		//	返回数据
		return Result.ok(infoIPage);

	}

}

